import React, { createContext, useState } from 'react';
import classNames from 'classnames';
import { TabItemProps } from './tabItem';
import TabItemTitle from './tabItemTitle';

type SelectCallback = (selectedIndex: number) => void;

export interface TabsProps {
  defaultIndex?: number;
  className?: string;
  style?: React.CSSProperties;
  onSelect?: SelectCallback;
}

export interface ITabsContext {
  index: number;
  onSelect?: SelectCallback;
}

export const TabsContext = createContext<ITabsContext>({
  index: 0
})


const Tabs: React.FC<TabsProps> = ({ className, style, children, defaultIndex, onSelect }) => {

  const classes = classNames('origin-tabs', className);
  const [active, setActive] = useState(defaultIndex);

  const handleClick: SelectCallback = (index: number) => {
    setActive(index);
    if (onSelect) {
      onSelect(index);
    }
  }

  const passedContext: ITabsContext = {
    index: active ? active : 0,
    onSelect: handleClick
  }

  const renderChildren = () => {
    // 标题
    const childrenTitleComponent = React.Children.map(children, (child, index) => {
      const childElement = child as React.FunctionComponentElement<TabItemProps>;
      if (childElement.type.displayName === 'TabItem') {
        return (<TabItemTitle index={index}>{ childElement.props.label }</TabItemTitle>)
      } else {
        console.error('warning: menu');
      }
    }) || [];
    // 内容
    const childrenContentComponent = React.Children.map(children, (child, index) => {
      const childElement = child as React.FunctionComponentElement<TabItemProps>;
      if (childElement.type.displayName === 'TabItem') {
        return React.cloneElement(childElement, {
          index
        })
      } else {
        console.error('warning: menu');
      }
    }) || [];
    return (
      <>
        <ul className="origin-tabs-nav-list">
          {childrenTitleComponent} 
        </ul>
        <div className="origin-tabs-content">
          { childrenContentComponent }
        </div>
      </>
    )
  }
  
  return (
    <div className={classes} style={style} >
      <TabsContext.Provider value={passedContext}>
        {renderChildren()}
      </TabsContext.Provider>
    </div>
  )
}

Tabs.defaultProps = {
  defaultIndex: 0
}

export default Tabs;